package top.iflyoung.cim.biz.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.iflyoung.cim.biz.entity.ChatGroup;
import top.iflyoung.cim.biz.entity.ChatGroupMember;
import top.iflyoung.cim.biz.entity.User;
import top.iflyoung.cim.biz.mapper.ChatGroupMemberMapper;
import top.iflyoung.cim.biz.service.ChatGroupMemberService;
import top.iflyoung.cim.biz.service.ChatGroupService;
import top.iflyoung.cim.common.util.VerifyUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liguiyang
 * @description
 * @sine 1.8
 * @date 2021/9/222:46
 **/
@Service("chatGroupMemberService")
public class ChatGroupMemberServiceImpl extends ServiceImpl<ChatGroupMemberMapper, ChatGroupMember> implements ChatGroupMemberService {
    @Autowired
    private ChatGroupService chatGroupService;

    @Override
    @Transactional
    public boolean addMembers(User creator, List<User> memberList) {
        if (VerifyUtil.isEmpty(memberList) || VerifyUtil.isEmpty(creator) || VerifyUtil.isEmpty(creator.getId())) {
            return false;
        }
        ChatGroup group = new ChatGroup();
        group.setCreatorID(creator.getId());
        group.setName(creator.getName() + "创建的群");
        if (chatGroupService.addAndGetId(group) > 0) {
            List<ChatGroupMember> members = new ArrayList<>();
            for (User user : memberList) {
                ChatGroupMember member = new ChatGroupMember();
                member.setMemberId(user.getId());
                member.setGroupId(group.getId());
                members.add(member);
            }
            return this.saveBatch(members);
        }
        return false;
    }

    public List<ChatGroupMember> findMembers(Long groupId) {
        if (VerifyUtil.isEmpty(groupId)) {
            return null;
        }
        return baseMapper.queryAllByGroupId(groupId);
    }
}
